package Comprehensive_04;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Test5 implements Runnable {
    private WriteWords writeWords;
    private static boolean flag = true;
    private static final Lock lock = new ReentrantLock();
    private static final Condition conA = lock.newCondition();
    private static final Condition conB = lock.newCondition();

    public Test5(WriteWords writeWords) {
        this.writeWords = writeWords;
    }


    @Override
    public void run() {
        int count = 0;
        String name = Thread.currentThread().getName();

        while (true) {
            try {
                lock.lock();
                if (writeWords.getCount() <= 0) {
                    conA.signal();
                    conB.signal();
                    break;
                }
                int leftCount = writeWords.getCount();
                if (flag) {
                    System.out.println(name + "线程-抄写一遍" +
                            writeWords.getWord() + ",两人总共还需要抄写" + --leftCount + "次");
                    writeWords.setCount(leftCount);
                    count++;
                    flag = false;
                    conB.signal();
                    conA.await();
                } else {
                    System.out.println(name + "线程-抄写一遍" +
                            writeWords.getWord() + "两人总共还需要抄写" + --leftCount + "次");
                    writeWords.setCount(leftCount);
                    count++;
                    flag = true;
                    conA.signal();
                    conB.await();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
        System.out.println(name + "线程一共抄写了" + count + "次");
    }

    public static void main(String[] args) {
        WriteWords words = new WriteWords(100, "HellowWorld");
        Thread t1 = new Thread(new Test5(words), "小王");
        Thread t2 = new Thread(new Test5(words), "小明");

        t1.start();
        t2.start();


    }
}

class WriteWords {
    private int count;
    private String word;


    public WriteWords() {
    }

    public WriteWords(int count, String word) {
        this.count = count;
        this.word = word;
    }

    /**
     * 获取
     *
     * @return count
     */
    public int getCount() {
        return count;
    }

    /**
     * 设置
     *
     * @param count
     */
    public void setCount(int count) {
        this.count = count;
    }

    /**
     * 获取
     *
     * @return word
     */
    public String getWord() {
        return word;
    }

    /**
     * 设置
     *
     * @param word
     */
    public void setWord(String word) {
        this.word = word;
    }

    public String toString() {
        return "WriteWords{count = " + count + ", word = " + word + "}";
    }
}

